const { cartFormatError,deleteCartError } = require("../constants/err.type.js")
const {createOrUpdate, findCarts,updateCarts,deleteCarts,selectCartOrUnselect } = require("../server/cart.server.js")

class CartController {
  // 添加至购物车
  async add(ctx) {
    // 解析userid goodsid
    const user_id = ctx.state.user.id
    const goods_id = ctx.request.body.goods_id

    // 操作数据库
    /*
      是否是第一次添加 第一次添加 create 否则 number 自增
    */

    const res = await createOrUpdate(user_id, goods_id)

    // 返回结果
    ctx.body = {
      code: 0,
      message: '加入购物车成功',
      result: res
    }


  }

  async findAll(ctx) {
    const {pageNum = 1, pageSize = 10} = ctx.request.query

    const res = await findCarts(pageNum, pageSize)

    ctx.body = {
      code: 0,
      message: '获取购物车列表成功',
      result: res
    }
  }
  // 更新购物车
  async update(ctx){
    const { id } = ctx.request.params
    const { number,selected } = ctx.request.body
    if(number === undefined &&  selected === undefined) {
      cartFormatError.message = "number和selected不能同时为空"
      return ctx.app.emit('error',cartFormatError,ctx)
    }
    console.log(333)
    const res = await updateCarts({id,number,selected})
    console.log("res",res)
    ctx.body = {
      code:0,
      message:'更新购物车成功',
      result:res
    }
  }
  // 删除购物车
  async deleteCart(ctx){
    try {
      const {ids} = ctx.request.body

      const res = await deleteCarts(ids)
      if(res){
        ctx.body = {
          code:0,
          message:'删除购物车成功',
          result:res
        }
      }else{
        ctx.app.emit('error',cartFormatError,ctx)
      }
    }catch (error) {
      console.log(error)
      ctx.app.emit('error',deleteCartError,ctx)
    }

  }

  // 全选与全不选
  async selectOrUnselect(ctx){
    const {id}  = ctx.state.user;
    const {selected} = ctx.request.body
    const res = await selectCartOrUnselect(id,selected)
    let msg ;
    if(selected){
      msg = "全部选中"
    }else{
      msg = "取消全选"
    }
    ctx.body = {
      code:0,
      message:msg,
      result:res
    }
  }
}

module.exports = new CartController()
